import axios from 'axios';

/**
 * A simple uuid generator, support prefix and template pattern.
 * @example
 *  uuid('v-') // -> v-xxx
 *  uuid('v-ani-%{s}-translate')  // -> v-ani-xxx
 */
export function uuid(prefix) {
  const id = Math.floor(Math.random() * 10000).toString(36);
  return prefix
    ? ~prefix.indexOf("%{s}")
      ? prefix.replace(/%\{s\}/g, id)
      : prefix + id
    : id;
}

export const getUUID = function () {
  var s = [];
  var hexDigits = "0123456789abcdef";
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = "-";
  var uuid = s.join("");
  return uuid;
};

export const getRole = function () {
  const userInfo = sessionStorage.getItem("userInfo");
  return userInfo ? JSON.parse(userInfo).roleName : "";
};

/**
 * 获取用户的政区
 * @returns {code: str, data: Array, codeList: Array}
 */
export const getUserRegion = function () {
  const userregion = sessionStorage.getItem("userRegion");
  return userregion ? JSON.parse(userregion) : {};
};

// 获取省市县code简写
export const getSubRegion = function (code) {
  let ncode = Number(code)
  if (ncode % 10000 === 0) {
    ncode = ncode / 10000
  } else if (ncode % 100 === 0) {
    ncode = ncode / 100
  }
  return ncode
}

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null;
  }
  const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string") {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time);
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), "/");
      }
    }

    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    return value.toString().padStart(2, "0");
  });
  return time_str;
}

export const getRegionGeomtry = async function (pcode, regionCode) {
  if (pcode == "1") {
    pcode = 100000;
  }
  let data;
  await axios.get(`/json/${pcode}.json`).then((res) => {
    let arr = res.data.features;
    data = arr.find((item) => {
      return item.properties.adcode == regionCode;
    });
  });
  return data;
};

// 根据多个regoncode查找政区边界的geojson数据
// async 返回的是Promise对象
// async里return xxx 相当于 return Promise.resolve(xxx)
export const getRegionjson = async function (list, type) {
  if (list.length === 1) {
    if (type === 1) {
      // 此处相当于return Promise.resolve(getRegionBorder(list))
      // getRegionBorder返回的是Promise对象，此处就相当于resolve了
      return getRegionBorder(list)
    } else if (type === 2) {
      return getRegionChildrensBorder(list)
    } else if (type === 3) {
      // await的后面如果是Promise对象，那么await的返回值就是Promise对象的resolve/reject返回结果。
      return [await getRegionBorder(list), await getRegionChildrensBorder(list)]
    } else {
      return null
    }
  } else {
    let curcodes = list.map((r) => Number(r.code));
    let res = await axios.get('/json/region.json');
    let pset = new Set()
    res.data.forEach((item) => {
      if (curcodes.includes(Number(item.code))) {
        pset.add(Number(item.pcode))
      }
    });
    let pcodes = Array.from(pset)
    let plist = pcodes.map((pc) => axios.get(`/json/${pc === 1 ? 100000 : pc}.json`));
    let result = await Promise.all(plist);
    let json = {
      type: 'FeatureCollection',
      features: []
    };
    for (let rs of result) {
      let arr = rs.data.features;
      let rlt = arr.filter((item) => curcodes.includes(item.properties.adcode));
      json.features.push(...rlt);
    }
    return json
  }
}

const getRegionBorder = async function (list) {
  let cur = list[0];
  let { code, pcode } = cur;
  pcode = pcode == '1' ? 100000 : pcode;
  if (code == '1') {
    return null
  } else {
    let rsd = await axios.get(`/json/${pcode}.json`)
    let arr = rsd.data.features;
    return arr.find((item) => item.properties.adcode == code)
  }
}

const getRegionChildrensBorder = async function (list) {
  let cur = list[0];
  let result = await axios.get(`/json/${cur.code == '1' ? 100000 : cur.code}.json`);
  return result.data;
}

/**
 * 附近位置最大最小经纬度计算 
 * @param   latitude   纬度
 * @param   longitude  经度
 * @param   distince    距离（千米）
 * @returns 格式：经度最小值 经度最大值 纬度最小值 纬度最大值
 */
export const getMaxMinLngLat = function (latitude, longitude, distince) {
  let r = 6371393;    // 地球半径米
  let lng = longitude;
  let lat = latitude;
  let dlng = 2 * Math.asin(Math.sin(distince / (2 * r)) / Math.cos(lat * Math.PI / 180));
  dlng = dlng * 180 / Math.PI;// 角度转为弧度
  let dlat = distince / r;
  dlat = dlat * 180 / Math.PI;
  let minlat = lat - dlat;
  let maxlat = lat + dlat;
  let minlng = lng - dlng;
  let maxlng = lng + dlng;
  return [minlng, maxlng, minlat, maxlat];
}

/**
 * 树形数组中，根据查找某个元素的所有父节点
 * @param {*} treeList 
 * @param {*} code 
 * @param {*} path 
 * @returns 返回所有父节点的数组
 */
const findParent = function (treeList, code, path = []) {
  if (!treeList) return [];
  for (const data of treeList) {
    path.push(data);
    if (data.url == code) return path;
    if (data.childrenList && data.childrenList.length) {
      const findchildren = this.findParent(data.childrenList, code, path);
      if (findchildren.length) return findchildren;
    }
    path.pop();
  }
  return [];
}

// 把两个对象数组合并
export const mergeUniquely = function (arr1 = [], arr2 = []) {
  const newArr = arr1.concat(arr2);
  newArr.sort((a, b) => b.value - a.value)
  const map = {};
  const res = [];
  newArr.forEach(el => {
    if (!map[el['name']]) {
      res.push(el);
      map[el['name']] = 1;
    }
  })
  return res
}

export const findChildUrl = function (obj) {
  let url = '';
  if (obj.children && obj.children.length) {
    let first = obj.children[0];
    url = findChildUrl(first);
  } else {
    url = obj.path;
  }
  return url;
}